<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>商品管理</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="../js/authChecker.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background: #f2f2f2;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Microsoft YaHei", Arial;
        }

        .page-title {
            font-size: 22px;
            color: #333;
            margin-bottom: 20px;
            font-weight: 600;
        }

        .el-button--primary {
            background: #FF1493;
            border-color: #FF1493;
        }

        .el-button--primary:hover,
        .el-button--primary:focus {
            background: #FF1493;
            border-color: #FF1493;
        }

        .el-button--warning {
            background-color: transparent !important;
            border-color: #E6A23C !important;
            color: #E6A23C !important;
        }

        .search-box {
            background: #fff;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
        }

        .goods-avatar {
            width: 60px;
            height: 60px;
            border-radius: 4px;
            object-fit: cover;
        }

        .el-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }

        .el-table th,
        .el-table td {
            padding: 12px 0;
            border: 1px solid #ebeef5;
            text-align: center;
        }

        .el-table th {
            background-color: #f5f7fa;
            color: #909399;
            font-weight: bold;
        }

        .el-table tr:hover {
            background-color: #f5f7fa;
        }

        .el-pagination {
            margin-top: 15px;
            text-align: right;
        }

        .el-pagination button {
            padding: 0 6px;
            margin: 0 5px;
            border: 1px solid #dcdfe6;
            background: #fff;
            border-radius: 4px;
            cursor: pointer;
        }

        .el-pagination button:disabled {
            cursor: not-allowed;
            opacity: 0.5;
        }

        .el-tag {
            padding: 0 10px;
            border-radius: 4px;
            font-size: 12px;
            line-height: 24px;
        }

        .el-tag--success {
            background-color: #f0f9eb;
            border-color: #e1f3d8;
            color: #67c23a;
        }

        .el-tag--info {
            background-color: #f4f4f5;
            border-color: #e9e9eb;
            color: #909399;
        }

        /* 加载动画 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            display: none;
        }

        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #FF1493;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
        /* 消息提示 - 仿示例样式 */
        .message {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            padding: 10px 20px;
            border-radius: 4px;
            /* 关键修改：背景、文字、边框色 */
            background-color: #f0f9eb;
            border: 1px solid #c2e7b0;
            color: #67c23a;
            z-index: 9999;
            display: none;
            align-items: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            opacity: 0;
        }

        /* 对勾图标样式 */
        .message i {
            font-family: "element-icons" !important;
            content: "\E652"; /* Element UI 成功图标 Unicode */
            margin-right: 8px;
            font-size: 16px;
            color: #67c23a;
        }

        /* 显示动画 */
        .message.show {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
        }

        /* 隐藏动画 */
        .message.hide {
            opacity: 0;
            transform: translateX(-50%) translateY(-20px);
        }
        /* 对话框样式 */
        .dialog-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 2000;
            display: none;
            justify-content: center;
            align-items: center;
        }

        .dialog-container {
            width: 50%;
            min-width: 500px;
            max-width: 800px;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .dialog-header {
            padding: 15px 20px;
            border-bottom: 1px solid #ebeef5;
            font-size: 18px;
            color: #303133;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .dialog-close {
            font-size: 20px;
            color: #909399;
            cursor: pointer;
        }

        .dialog-close:hover {
            color: #FF1493;
        }

        .dialog-body {
            padding: 20px;
            max-height: 70vh;
            overflow-y: auto;
        }

        .dialog-footer {
            padding: 15px 20px;
            border-top: 1px solid #ebeef5;
            text-align: right;
        }

        /* 表单优化 */
        .form-row {
            display: flex;
            margin-bottom: 18px;
        }

        .form-label {
            width: 100px;
            text-align: right;
            padding-right: 12px;
            line-height: 36px;
            color: #606266;
        }

        .form-content {
            flex: 1;
        }

        .el-input__inner,
        .el-textarea__inner,
        .el-select {
            width: 100%;
            padding: 8px 15px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            color: #606266;
            outline: none;
        }

        .el-input__inner:focus,
        .el-textarea__inner:focus {
            border-color: #FF1493;
        }

        .el-textarea__inner {
            min-height: 80px;
            resize: vertical;
        }

        /* 图片上传优化 */
        .image-uploader {
            display: flex;
            align-items: flex-start;
        }

        .image-preview {
            width: 150px;
            height: 150px;
            border: 1px dashed #d9d9d9;
            border-radius: 4px;
            position: relative;
            overflow: hidden;
            margin-right: 20px;
        }

        .image-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .image-uploader-actions {
            display: flex;
            flex-direction: column;
        }

        .upload-tip {
            margin-top: 10px;
            color: #909399;
            font-size: 12px;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .dialog-container {
                width: 90%;
                min-width: auto;
            }

            .form-row {
                flex-direction: column;
            }

            .form-label {
                text-align: left;
                margin-bottom: 8px;
                width: auto;
            }

            .image-uploader {
                flex-direction: column;
            }

            .image-preview {
                margin-right: 0;
                margin-bottom: 15px;
            }

            .el-table th,
            .el-table td {
                padding: 12px 0;
                border: 1px solid #ebeef5;
                text-align: center;
                width: auto;
                min-width: 80px;
                white-space: nowrap;
            }

        }
    </style>
</head>
<body>
<div class="page-title">商品管理</div>
<div id="app">
    <div class="search-box">
        <form class="el-form el-form--inline" id="searchForm" onsubmit="return false;">
            <div class="el-form-item">
                <label class="el-form-item__label">商品名称</label>
                <div class="el-form-item__content">
                    <input type="text" class="el-input__inner" id="cakename" placeholder="请输入商品名称">
                </div>
            </div>
            <div class="el-form-item">
                <label class="el-form-item__label">状态</label>
                <div class="el-form-item__content">
                    <select class="el-select__inner" id="status" style="width:120px;height: 40px;">
                        <option value="">全部状态</option>
                        <option value="1">下架</option>
                        <option value="0">在售</option>
                    </select>
                </div>
            </div>
            <div class="el-form-item">
                <div class="el-form-item__content">
                    <!-- 修改搜索按钮 -->
                    <button type="button" class="el-button el-button--primary" onclick="handleSearch()"
                            style="background: transparent; color: #FF1493; border-color: #FF1493;">搜索</button>
                    <button type="button" class="el-button" onclick="resetSearch()"
                            style="color:#ff85a2;border-color:#ff85a2;">重置</button>
                </div>
            </div>
        </form>

        <div style="margin-top:10px;">
            <button type="button" class="el-button el-button--warning" id="batchToggleBtn" disabled
                    onclick="handleBatchToggle()">
                批量切换状态
            </button>
            <!-- 修改添加商品按钮 -->
            <button type="button" class="el-button el-button--primary"
                    style="background: transparent; color:#FF1493;border-color:#FF1493;" onclick="openAddDialog()">
                <i class="el-icon-plus"></i> 添加商品
            </button>
        </div>
    </div>

    <table class="el-table" id="goodsTable">
        <thead>
        <tr>
            <th style="width: 80px;"><input type="checkbox" id="selectAll" onclick="toggleSelectAll()"></th>
            <th style="width: 100px;">商品ID</th>
            <th>商品图片</th>
            <th>商品名称</th>
            <th style="width: 150px;">商品介绍</th>
            <th>商品分类</th>
            <th>基础价格(元)</th>
            <th>销量</th>
            <th>状态</th>
            <th style="width: 80px;">尺寸</th>
            <th>6寸价格</th>
            <th>创建时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- 动态内容将通过JS填充 -->
        </tbody>
    </table>

    <div class="el-pagination">
        <button class="el-pagination__first" onclick="firstPage()" id="firstBtn">首页</button>
        <button class="el-pagination__prev" onclick="prevPage()" id="prevBtn">上一页</button>第
        <span class="el-pagination__current" id="currentPage"
              style="width: 10px; text-align: center; font-size: 20px; margin: -2px -4px -20px -10px;">1</span>页
        <button class="el-pagination__next" onclick="nextPage()" id="nextBtn">下一页</button>
        <button class="el-pagination__last" onclick="lastPage()" id="lastBtn">尾页</button>
        <span class="el-pagination__total">共 <span id="totalItems">0</span> 条</span>
    </div>
</div>

<!-- 商品对话框 -->
<div class="dialog-overlay" id="goodsDialog">
    <div class="dialog-container">
        <div class="dialog-header">
            <span id="dialogTitle">新增商品</span>
            <span class="dialog-close" onclick="closeDialog()">×</span>
        </div>
        <div class="dialog-body">
            <form id="goodsForm">
                <div class="form-row">
                    <div class="form-label">商品图片</div>
                    <div class="form-content">
                        <div class="image-uploader">
                            <div class="image-preview">
                                <img id="dialogCakeImage" src="">
                            </div>
                            <div class="image-uploader-actions">
                                <button type="button" class="el-button el-button--primary"
                                        onclick="triggerUpload()">
                                    <i class="el-icon-upload"></i> 选择图片
                                </button>
                                <input type="file" id="fileUpload" style="display:none" accept="image/*"
                                       onchange="handleFileUpload(this.files)">
                                <div class="upload-tip">建议尺寸：800×800像素，大小不超过2MB</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-label">商品名称</div>
                    <div class="form-content">
                        <input type="text" class="el-input__inner" id="dialogCakename" placeholder="请输入商品名称"
                               required>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-label">商品描述</div>
                    <div class="form-content">
								<textarea class="el-textarea__inner" id="dialogCakedesc" placeholder="请输入商品描述"
                                          rows="3"></textarea>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-label">商品分类</div>
                    <div class="form-content">
                        <select class="el-select__inner" id="dialogCategoryid" required
                                style="height: 40px; width: 100px;">
                            <option value="">请选择分类</option>
                        </select>
                    </div>
                </div>

                <!-- 基础价格部分修改为 -->
                <div class="form-row">
                    <div class="form-label">基础价格(元)</div>
                    <div class="form-content">
                        <input type="number" class="el-input__inner" id="dialogCakeprice" min="1" step="1"
                               placeholder="0.00" required style="width: 500px;" oninput="validatePrice(this)">
                    </div>
                </div>

                <!-- 6寸价格部分修改为 -->
                <div class="form-row">
                    <div class="form-label">6寸价格(元)</div>
                    <div class="form-content">
                        <input type="number" class="el-input__inner" id="dialogCakepricebig" min="1" step="1"
                               placeholder="0.00" required style="width: 500px;" oninput="validatePrice(this)">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-label">尺寸</div>
                    <div class="form-content">
                        <input type="text" class="el-input__inner" id="dialogCakesize" placeholder="例如: [0]4寸/[1]6寸"
                               style="width: 500px;  ">
                    </div>
                </div>

                <div class="form-row" id="dialogSalesItem" style="display:none" style="margin-top: 10px;">
                    <div class="form-label" style="margin:26px -61px 15px 32px;width: -32px; ">销量</div>
                    <div class="form-content" style="margin: 23px -4px 25px 63px;">
                        <input type="text" class="el-input__inner" id="dialogCakesales"
                               style="width: 500px;background-color: lightgray;  " disabled readonly>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-label">状态</div>
                    <div class="form-content" style="margin: 8px 14px 28px 3px;">
                        <label style="margin-right: 20px;"><input type="radio" name="dialogStatus" value="1"
                                                                  checked> 在售</label>
                        <label><input type="radio" name="dialogStatus" value="0"> 下架</label>
                    </div>
                </div>
            </form>
        </div>
        <div class="dialog-footer">
            <button type="button" class="el-button" onclick="closeDialog()">取消</button>
            <button type="button" class="el-button el-button--primary" onclick="saveGoods()"
                    style="background: transparent; color: #FF1493; border-color: #FF1493;">保存</button>
        </div>
    </div>
</div>

<!-- 加载动画 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
</div>

<!-- 消息提示 -->
<div class="message" id="message"></div>

<script>
    // 在页面加载时立即检查登录状态
    if (!checkAdminLogin()) {
        // 登录检查失败，阻止页面继续加载
        console.log('登录验证失败，已跳转至登录页');
    } else {
        // 全局变量
        let tableData = [];
        let selectedRows = [];
        let categoryOptions = [];
        let currentPage = 1;
        let limit = 10;
        let total = 0;
        let isAdd = true;
        let currentFormData = {};

        // 页面加载完成后初始化
        $(document).ready(function() {
            fetchData();
            getCategoryListFront();
        });

        // 显示加载中
        function showLoading() {
            $('#loadingOverlay').css('display', 'flex');
        }

        // 隐藏加载中
        function hideLoading() {
            $('#loadingOverlay').hide();
        }

        // 显示消息（带动画）
        function showMessage(type, message) {
            const msgElement = $('#message');
            msgElement.removeClass().addClass(`message message-${type}`);
            msgElement.text(message);

            // 先应用离开动画重置位置
            msgElement.removeClass('show').addClass('hide');
            setTimeout(() => {
                // 再切换进入动画
                msgElement.removeClass('hide').addClass('show');
                msgElement.show();

                // 3秒后自动隐藏
                setTimeout(() => {
                    msgElement.removeClass('show').addClass('hide');
                    setTimeout(() => {
                        msgElement.hide();
                    }, 300);
                }, 3000);
            }, 300);
        }
        // 获取商品数据
        function fetchData() {
            showLoading();

            const params = {
                page: currentPage,
                limit: limit
            };

            if ($('#cakename').val()) {
                params.cakename = $('#cakename').val();
            }

            if ($('#status').val()) {
                params.status = $('#status').val();
            }

            $.ajax({
                url: 'http://localhost:8887/cake/getAllCake',
                type: 'GET',
                data: params,
                success: function(response) {
                    hideLoading();
                    if (response.code === 200) {
                        tableData = response.data.allCake.list || [];
                        total = response.data.allCake.total || 0;
                        console.log(tableData);
                        renderTable();
                        updatePagination();
                    } else {
                        showMessage('error', response.msgerr || '获取数据失败');
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    showMessage('error', '请求失败: ' + error);
                }
            });
        }

        // 渲染表格
        function renderTable() {
            const tbody = $('#goodsTable tbody');
            tbody.empty();

            tableData.forEach(function(row) {
                const tr = $('<tr>');

                tr.append(`
                       <td><input type="checkbox" data-id="${row.cakeid}" onchange="handleRowSelection(this, ${row.cakeid})" ${row.status === '0' ? 'disabled' : ''}></td>
                       <td>${row.cakeid}</td>
                       <td align="center"><img src="${row.cakeurl}" style="width: 50px;
				height: 50px;"></td>
                       <td>${row.cakename}</td>
                       <td>${row.cakedesc}</td>
                       <td>${row.categoryName}</td>
                       <td>¥${Number(row.cakeprice).toFixed(2)}</td>
                       <td>${row.cakesales}</td>
                       <td><span class="el-tag el-tag--${row.status == 0 ? 'success' : 'info'}" style="cursor:pointer" onclick="toggleStatus(${row.cakeid}, ${row.status}, '${row.cakename}')">${row.status == 0 ? '在售' : '下架'}</span></td>
                       <td>${row.cakesize==0 ?'4寸':'6寸'}</td>
                       <td>¥${Number(row.cakepricebig).toFixed(2)}</td>
                       <td>${row.createtime}</td>
                       <td>
                           <button class="el-button el-button--text" onclick="openEditDialog(${row.cakeid})">
                               <i class="el-icon-edit"></i> 编辑
                           </button>
                       </td>
                   `);

                tbody.append(tr);
            });

            // 更新批量操作按钮状态
            $('#batchToggleBtn').prop('disabled', selectedRows.length === 0);
        }

        // 上一页
        function prevPage() {
            if (currentPage > 1) {
                currentPage--;
                fetchData();
            }
        }

        // 下一页
        function nextPage() {
            if (currentPage * limit < total) {
                currentPage++;
                fetchData();
            }
        }

        // 首页
        function firstPage() {
            if (currentPage > 1) {
                currentPage = 1;
                fetchData();
            }
        }

        // 尾页
        function lastPage() {
            if (currentPage * limit < total) {
                currentPage = Math.ceil(total / limit);
                fetchData();
            }
        }

        // 更新分页状态
        function updatePagination() {
            $('#currentPage').text(currentPage);
            $('#totalItems').text(total);

            const prevBtn = $('#prevBtn');
            const nextBtn = $('#nextBtn');
            const firstBtn = $('#firstBtn');
            const lastBtn = $('#lastBtn');

            prevBtn.prop('disabled', currentPage <= 1);
            nextBtn.prop('disabled', currentPage * limit >= total);
            firstBtn.prop('disabled', currentPage <= 1);
            lastBtn.prop('disabled', currentPage * limit >= total);
        }

        // 搜索
        function handleSearch() {
            currentPage = 1;
            fetchData();
        }

        // 重置搜索
        function resetSearch() {
            $('#cakename').val('');
            $('#status').val('');
            handleSearch();
        }

        // 处理行选择
        function handleRowSelection(checkbox, cakeid) {
            if (checkbox.checked) {
                const row = tableData.find(item => item.cakeid === cakeid);
                if (row) {
                    selectedRows.push(row);
                }
            } else {
                selectedRows = selectedRows.filter(item => item.cakeid !== cakeid);
            }

            // 更新全选状态
            updateSelectAllStatus();

            // 更新批量操作按钮状态
            $('#batchToggleBtn').prop('disabled', selectedRows.length === 0);
        }

        // 全选/取消全选
        function toggleSelectAll() {
            const selectAll = $('#selectAll').prop('checked');
            const checkboxes = $('#goodsTable tbody input[type="checkbox"]:not(:disabled)');

            checkboxes.each(function() {
                $(this).prop('checked', selectAll);
                const cakeid = parseInt($(this).data('id'));

                if (selectAll) {
                    const row = tableData.find(item => item.cakeid === cakeid);
                    if (row && !selectedRows.some(item => item.cakeid === cakeid)) {
                        selectedRows.push(row);
                    }
                } else {
                    selectedRows = selectedRows.filter(item => item.cakeid !== cakeid);
                }
            });

            $('#batchToggleBtn').prop('disabled', selectedRows.length === 0);
        }

        // 更新全选状态
        function updateSelectAllStatus() {
            const checkboxes = $('#goodsTable tbody input[type="checkbox"]:not(:disabled)');
            const selectAll = $('#selectAll');

            if (checkboxes.length === 0) {
                selectAll.prop('checked', false);
                return;
            }

            const allChecked = checkboxes.toArray().every(checkbox => checkbox.checked);
            selectAll.prop('checked', allChecked);
        }

        // 批量切换状态
        function handleBatchToggle() {
            const cakeIds = selectedRows.map(row => row.cakeid);

            if (cakeIds.length === 0) return;

            if (confirm(`确定切换 ${cakeIds.length} 件商品的状态吗？`)) {
                showLoading();

                $.ajax({
                    url: 'http://localhost:8887/cake/updateCakeHou',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        cakeId: cakeIds
                    }),
                    success: function(response) {
                        hideLoading();
                        if (response.code === 200) {
                            showMessage('success', '批量切换成功');
                            fetchData();
                            selectedRows = [];
                            $('#selectAll').prop('checked', false);
                        } else {
                            showMessage('error', response.msgerr || '批量切换失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        hideLoading();
                        showMessage('error', '请求失败: ' + error);
                    }
                });
            }
        }

        // 切换单个商品状态
        function toggleStatus(cakeid, currentStatus, cakename) {
            const newStatus = currentStatus === 0 ? 1 : 0;

            if (confirm(`确定切换 ${cakename} 的状态吗？`)) {
                showLoading();

                $.ajax({
                    url: 'http://localhost:8887/cake/updateCakeHou',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        cakeId: [cakeid],
                        status: newStatus
                    }),
                    success: function(response) {
                        hideLoading();
                        if (response.code === 200) {
                            showMessage('success', '状态已切换');
                            fetchData();
                        } else {
                            showMessage('error', response.msgerr || '切换失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        hideLoading();
                        showMessage('error', '请求失败: ' + error);
                    }
                });
            }
        }

        // 打开添加对话框
        function openAddDialog() {
            isAdd = true;
            $('#dialogTitle').text('新增商品');
            $('#dialogSalesItem').hide();

            // 重置表单
            $('#dialogCakeImage').attr('src', '../img/空白页.png');
            $('#dialogCakename').val('');
            $('#dialogCakedesc').val('');
            $('#dialogCakeprice').val('');
            $('#dialogCakepricebig').val('');
            $('#dialogCakesize').val('');
            $('input[name="dialogStatus"][value="1"]').prop('checked', true);

            // 清空当前表单数据
            currentFormData = {
                cakename: '',
                cakedesc: '',
                categoryid: null,
                cakeprice: 0,
                cakepricebig: 0,
                cakesales: 0,
                cakesize: '',
                status: 1,
                cakeurl: ''
            };

            // 确保分类选项已加载
            renderCategoryOptions();

            $('#goodsDialog').css('display', 'flex');
        }

        // 打开编辑对话框
        function openEditDialog(cakeid) {
            const row = tableData.find(item => item.cakeid === cakeid);
            if (!row) return;

            isAdd = false;
            $('#dialogTitle').text('编辑商品');
            $('#dialogSalesItem').show();

            // 填充表单
            $('#dialogCakeImage').attr('src', row.cakeurl || '../img/logo.png');
            $('#dialogCakename').val(row.cakename);
            $('#dialogCakedesc').val(row.cakedesc);
            $('#dialogCakeprice').val(row.cakeprice);
            $('#dialogCakepricebig').val(row.cakepricebig);
            $('#dialogCakesize').val(row.cakesize);
            $('#dialogCakesales').val(row.cakesales);
            $(`input[name="dialogStatus"][value="${row.status}"]`).prop('checked', true);

            // 保存当前表单数据
            currentFormData = $.extend({}, row);

            // 确保分类选项已加载
            renderCategoryOptions();

            $('#goodsDialog').css('display', 'flex');
        }

        // 关闭对话框
        function closeDialog() {
            $('#goodsDialog').hide();
        }

        // 触发文件上传
        function triggerUpload() {
            $('#fileUpload').click();
            console.log("不是真的")
        }

        // 保存商品
        function saveGoods() {
            // 表单验证
            if (!$('#dialogCakename').val().trim()) {
                showMessage('error', '请输入商品名称');
                $('#dialogCakename').focus();
                return;
            }

            if (!$('#dialogCategoryid').val()) {
                showMessage('error', '请选择商品分类');
                $('#dialogCategoryid').focus();
                return;
            }

            if (!$('#dialogCakeprice').val() || parseFloat($('#dialogCakeprice').val()) < 0) {
                showMessage('error', '请输入有效的基础价格');
                $('#dialogCakeprice').focus();
                return;
            }

            if (!$('#dialogCakepricebig').val() || parseFloat($('#dialogCakepricebig').val()) < 0) {
                showMessage('error', '请输入有效的6寸价格');
                $('#dialogCakepricebig').focus();
                return;
            }

            // 收集表单数据
            const formData = {
                cakename: $('#dialogCakename').val().trim(),
                cakedesc: $('#dialogCakedesc').val().trim(),
                categoryid: $('#dialogCategoryid').val(),
                cakeprice: parseFloat($('#dialogCakeprice').val()) || 0,
                cakepricebig: parseFloat($('#dialogCakepricebig').val()) || 0,
                cakesize: $('#dialogCakesize').val().trim(),

                status: parseInt($('input[name="dialogStatus"]:checked').val()),
                cakeurl: $('#dialogCakeImage').attr('src') === '../img/logo.png' ? '' : $('#dialogCakeImage').attr(
                    'src')
            };

            // 如果是编辑，添加 cakeid
            if (!isAdd) {
                formData.cakeid = currentFormData.cakeid;
                formData.cakesales = currentFormData.cakesales;
                formData.createtime = currentFormData.createtime; // 添加创建时间

                console.log(formData);
            }

            showLoading();

            const url = isAdd ?
                'http://localhost:8887/cake/insertCakeInfo' :
                'http://localhost:8887/cake/updateCakeInfo';

            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    hideLoading();
                    if (response.code === 200) {
                        showMessage('success', '添加成功');
                        closeDialog();
                        fetchData();
                    } else {
                        // showMessage('error', response.msgerr || (isAdd ? '添加失败' : '保存失败'));
                        showMessage('error', '添加失败');
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    showMessage('error', '请求失败: ' + error);
                }
            });
        }

        // 获取分类列表
        function getCategoryListFront() {
            showLoading();

            $.ajax({
                url: 'http://localhost:8887/category/getCategoryListFront',
                type: 'GET',
                success: function(response) {
                    hideLoading();
                    if (response.code === 200) {
                        categoryOptions = response.data.categoryList || [];
                        renderCategoryOptions();
                    } else {
                        showMessage('error', response.msgerr || '获取分类失败');
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    showMessage('error', '请求失败: ' + error);
                }
            });
        }

        // 渲染分类选项
        function renderCategoryOptions() {
            const select = $('#dialogCategoryid');
            select.empty().append('<option value="">请选择分类</option>');

            categoryOptions.forEach(function(category) {
                select.append($('<option>', {
                    value: category.categoryid,
                    text: category.categoryname
                }));
            });

            // 如果有当前表单数据，设置选中的分类
            if (currentFormData.categoryid) {
                select.val(currentFormData.categoryid);
            }
        }

        // 价格验证函数
        function validatePrice(input) {
            if (input.value && parseFloat(input.value) < 1) {
                input.value = 1;
                showMessage('error', '价格不能低于1元');
            }
        }

        // 处理文件上传
        function handleFileUpload(files) {
            if (!files || files.length === 0) return;

            const file = files[0];
            const isImg = file.type.startsWith('image/');
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImg) {
                showMessage('error', '只能上传图片文件');
                return;
            }

            if (!isLt2M) {
                showMessage('error', '图片大小不能超过2MB');
                return;
            }

            // 预览图片
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#dialogCakeImage').attr('src', e.target.result);
            };
            reader.readAsDataURL(file);

            // 上传到服务器
            showLoading();

            const formData = new FormData();
            formData.append('file', file);
            console.log(formData);
            $.ajax({
                url: 'http://localhost:8887/upload/categoryImage',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    hideLoading();
                    if (response.code === 200) {
                        $('#dialogCakeImage').attr('src', response.data.url);
                        showMessage('success', '图片上传成功');
                    } else {
                        showMessage('error', response.msg || '上传失败');
                        $('#dialogCakeImage').attr('src', '../img/logo.png');
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    showMessage('error', '上传失败: ' + error);
                    $('#dialogCakeImage').attr('src', '../img/logo.png');
                }
            });
        }
    }
</script>
</body>
</html>